package com.zxjbyte.yiyi.framework.common.core.okhttp;

import cn.hutool.core.util.ObjectUtil;
import com.zxjbyte.yiyi.framework.common.core.okhttp.callback.IProgressCallback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.lang.Nullable;

import java.io.IOException;

/**
 * 对请求体进行包装。这个类实现了 RequestBody 接口，它的作用是在上传请求时，将上传的字节数保存在内部的计数器中
 * @Author zhangxingjia
 * @Date 2023/4/28 10:45
 * @Version: 1.0
 */
public class CountingRequestBody extends RequestBody {

    private final RequestBody requestBody;
    private final IProgressCallback progressCallback;

    public CountingRequestBody(RequestBody requestBody, IProgressCallback progressCallback) {
        this.requestBody = requestBody;
        this.progressCallback = progressCallback;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return requestBody.contentLength();
    }

    @Override
    public void writeTo(@NotNull BufferedSink sink) throws IOException {
        CountingSink countingSink = new CountingSink(sink);
        BufferedSink bufferedSink = Okio.buffer(countingSink);
        requestBody.writeTo(bufferedSink);
        bufferedSink.flush();
    }

    private final class CountingSink extends ForwardingSink {

        private long bytesWritten = 0;
        private long contentLength = 0L;

        public CountingSink(@NotNull Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(@NotNull Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            if (contentLength == 0) {
                contentLength = contentLength();
            }
            bytesWritten += byteCount;
            progressCallback.onUploadProgress(bytesWritten, contentLength , ObjectUtil.equal(bytesWritten, contentLength));
        }
    }
}
